package com.garbuz.svnadmin.data
{
	import actionlib.common.query.from;
	import actionlib.common.query.mappers.nameField;

	import com.garbuz.svnadmin.dto.UserResponseTO;
	import com.garbuz.svnadmin.services.UserService;

	import mx.collections.ArrayCollection;

	public class UsersDataProvider extends DataProviderBase
	{
		[Bindable]
		public var users:ArrayCollection;
		
		[Bindable]
		public var groups:ArrayCollection;

		override public function retrieveData():void
		{
			getBusy();
			getService().getUsers();
		}

		public function createUser(userName:String):void
		{
			getBusy();
			getService().createUser(userName);
		}

		public function removeUser(userName:String):void
		{
			getBusy();
			getService().removeUser(userName);
		}

		public function addGroup(groupName:String):void
		{
			getBusy();
			getService().createGroup(groupName);
		}

		public function removeGroup(groupName:String):void
		{
			getBusy();
			getService().removeGroup(groupName);
		}

		public function submitGroupUsers(groupName:String, users:Object):void
		{
			var userNames:Vector.<String> = Vector.<String>(from(users).select(nameField));

			getBusy();
			getService().submitGroupUsers(groupName, userNames);
		}

		public function submitUserGroups(userName:String, groups:Object):void
		{
			var groupNames:Vector.<String> = Vector.<String>(from(groups).select(nameField));

			getBusy();
			getService().submitUserGroups(userName, groupNames);
		}

		public function setPassword(userName:String, hash:String):void
		{
			getBusy();
			getService().setPassword(userName, hash);
		}

		private function onResult(result:UserResponseTO):void
		{
			var usersArray:Array = from(result.users).select(User.fromTO);
			usersArray.sortOn("name", Array.CASEINSENSITIVE);
			users = new ArrayCollection(usersArray);

			var groupsArray:Array = from(result.groups).select(Group.fromTO);
			groupsArray.sortOn("name", Array.CASEINSENSITIVE);
			groups = new ArrayCollection(groupsArray);

			getReady();
		}

		public function getUsersInGroup(groupName:String):Array
		{
			return from(users)
					.where(function (user:User):Boolean { return user.hasGroup(groupName) })
					.select();
		}

		public function getUserGroups(user:User):Array
		{
			return from(groups)
					.where(function (group:Group):Boolean { return user.hasGroup(group.name) })
					.select();
		}

		protected function getService():UserService
		{
			return new UserService(onResult, onServiceError);
		}

	}
}
